// 简单前端逻辑：登录、创建/列出/删除账单、时间段汇总
(function(){
  const apiBase = '/api';
  // token / username 存 localStorage
  function setToken(t){ localStorage.setItem('authToken', t); }
  function getToken(){ return localStorage.getItem('authToken'); }
  function clearToken(){ localStorage.removeItem('authToken'); localStorage.removeItem('username'); }
  function setUsername(u){ localStorage.setItem('username', u); }
  function getUsername(){ return localStorage.getItem('username'); }

  // 登录页
  const btnLogin = document.getElementById('btnLogin');
  if (btnLogin){
    btnLogin.addEventListener('click', async ()=>{
      const username = document.getElementById('username').value;
      const password = document.getElementById('password').value;
      const res = await fetch(`${apiBase}/users/login?username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}`, { method: 'POST' });
      if (res.ok){
        const obj = await res.json();
        setToken(obj.token);
        setUsername(obj.username);
        window.location.href = '/bills.html';
      } else {
        document.getElementById('loginMsg').textContent = '登录失败';
      }
    });
  }

  // bills 页初始化
  async function initBills(){
    const token = getToken();
    if (!token) { window.location.href = '/index.html'; return; }

    document.getElementById('btnLogout').addEventListener('click', ()=>{ clearToken(); window.location.href = '/index.html'; });
    // 显示用户名
    const uname = getUsername();
    if (uname){
      const h = document.createElement('div');
      h.className = 'text-muted';
      h.textContent = '当前用户：' + uname;
      document.querySelector('.d-flex.justify-content-between').appendChild(h);
    }

    document.getElementById('btnCreate').addEventListener('click', async ()=>{
      const amount = parseFloat(document.getElementById('amount').value);
      const type = document.getElementById('type').value;
      const description = document.getElementById('description').value;
      const body = { amount, type, description };
      const res = await fetch(`${apiBase}/bills`, { method: 'POST', headers: { 'Content-Type':'application/json', 'X-Auth-Token': token }, body: JSON.stringify(body) });
      if (res.ok){ loadList(); }
    });

    document.getElementById('btnSummary').addEventListener('click', async ()=>{
      const from = document.getElementById('from').value;
      const to = document.getElementById('to').value;
      const q = [];
      if (from) q.push('from=' + encodeURIComponent(new Date(from).toISOString()));
      if (to) q.push('to=' + encodeURIComponent(new Date(to).toISOString()));
      const res = await fetch(`${apiBase}/bills/summary?${q.join('&')}`, { headers: { 'X-Auth-Token': token } });
      if (res.ok){
        const sum = await res.json();
        document.getElementById('summaryResult').textContent = '总额：' + sum;
      }
    });

    window.loadList = async function(){
      const res = await fetch(`${apiBase}/bills`, { headers: { 'X-Auth-Token': token } });
      if (!res.ok) return;
      const data = await res.json();
      const tbody = document.querySelector('#billsTable tbody');
      tbody.innerHTML = '';
      data.forEach(b => {
        const tr = document.createElement('tr');
  tr.innerHTML = `<td>${new Date(b.createdAt).toLocaleString()}</td><td>${b.amount}</td><td>${b.type}</td><td>${b.description||''}</td><td><button data-id="${b.id}" class="del btn btn-sm btn-danger">删除</button></td>`;
        tbody.appendChild(tr);
      });
      tbody.querySelectorAll('.del').forEach(btn => btn.addEventListener('click', async (e)=>{
        const id = e.target.dataset.id;
        await fetch(`${apiBase}/bills/${id}`, { method: 'DELETE', headers: { 'X-Auth-Token': token } });
        loadList();
      }));
    };

    loadList();
  }

  if (window.location.pathname.endsWith('/bills.html')) initBills();
})();